<?php
namespace app\mbyz\controller;
use think\Request;
use \Qcloud\Sms\SmsSingleSender;
use app\common\model\SmsCodesModel;
use think\Db;
use think\facade\Session;
class Wxlogin
{
    public function login(Request $request)
    {
        $paramData = $request->param();
        Session::set('room', isset($paramData['room'])?$paramData['room']:'');
        Session::set('num', isset($paramData['num'])?$paramData['num']:'');
        $REDIRECT_URI=config('app.app_host') . '/mbyz/callback';
        $scope='snsapi_base';
        $state = 'xian20170930';
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wx.app_id').'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
        header("Location:".$url);
    }
    public function callback(Request $request)
    {
        $data = [];
        $data['errcode'] = 200;
        $postData = $request->param();
        if (isset($postData['code']))
        {
            $code = $postData['code'];
        }
        else
        {
            $data['errcode'] = 400;
            $data['errmsg'] = '缺少code';
            return json_encode($data);
        }
        $appid = config('wx.app_id');
        $secret = config('wx.secret');
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
        $result = httpRequest($get_token_url);
        Session::set('openid', $result['openid']);
        Db::table('mbyz_total')->where('total_object','mbyz')->setInc('page_view');
        return view('mbyz/index', $result);
        
    }
    public function check_register(Request $request)
    {
        $paramData = $request->param();
        $openid = Session::get('openid');
        $service_url = 'https://wxzhsc.sasseur.com/api/v3/securities/devices/register?deviceId='.$paramData['device_id'].'&appKey=P23GQJU5LH&rnd='.GetfourNumber(4); 
        $result = httpRequest($service_url, 1);
        if ($result['errorCode'] != 'PUB-00000')
        {
            $data['errcode'] = 400;
            $data['errmsg']  = '参数错误';
            return json_encode($data);
        }
        
        Session::set('accessToken', $result['body']['accessToken']);
        $param = [];
        $param['accessToken'] = $result['body']['accessToken'];
        $param['rnd'] = GetfourNumber(4);
        $param['appKey'] = 'P23GQJU5LH';
        $param['timestamp'] = time();
        $param['signType'] = 'md5';
        $param['type'] = 'app_weixin';
        $param['value'] = $openid;
        $sign = makeSign($param);
        //查询是否注册
        $url = 'https://wxzhsc.sasseur.com/api/v3/member/simple/info?accessToken='.$param['accessToken'].'&rnd='.$param['rnd'].'&appKey='.$param['appKey'].'&timestamp='.$param['timestamp'].'&sign='.$sign.'&signType='.$param['signType'].'&type=app_weixin&value='.$openid;

        $results = httpRequest($url);
        $data = [];
        $data['room'] = Session::get('room');
        $data['num'] = Session::get('num');
        if ($results['errorCode'] == 'PUB-00000')
        {
            if (empty($results['body']['phone']))
            {
                $data['errcode'] = 400;
                $data['errmsg'] = '未注册';
                return json_encode($data);
            }
            Db::table('mbyz_total')->where('total_object','mbyz')->setInc('login_number');
            $data['errcode'] = 200;
            $data['errmsg'] = '已注册';
            $data['data'] = $results;
            return json_encode($data);
        }
        else
        {
            $data['errcode'] = 400;
            $data['errmsg']  = '未注册';
            return json_encode($data);
        }
    }
    public function send_page()
    {
        return view('mbyz/login');
    }
    public function send_msg(Request $request)
    {
        $postData = $request->param();
        
        $sms_code = new SmsCodesModel;
        $sms_code->phone = $postData['phone'] ;
        $sms_code->created_at = date('Y-m-d H:i:s');
        $sms_code->code = rand(1000, 9999) ;
        $sms_code->save();

        // 请根据实际 appid 和 appkey 进行开发，以下只作为演示 sdk 使用
        $appid = 1400034753;
        $appkey = "99539b9e36de406c14984c9305192a05";
        $templId = 26569;

        $phone = $sms_code->phone ;
        $params = array('砂之船西安奥莱'  , $sms_code->code, "10");
        
        $singleSender = new SmsSingleSender($appid, $appkey);
        $result = $singleSender->sendWithParam("86", $phone, $templId, $params, "", "", "");
        $rsp = json_decode($result, true);

        $sms_code->result = $rsp['result'];
        $sms_code->errmsg = $rsp['errmsg'];

        if ($sms_code->result == 0)
        {
            $sms_code->ext = $rsp['ext'];
            $sms_code->sid = $rsp['sid'];
            $sms_code->fee = $rsp['fee'];
        }
        
        $sms_code->save() ;
        $data = [];
        $data['errcode'] = $sms_code->result;
        $data['errmsg'] = $sms_code->errmsg;
        $data['code'] = $sms_code->code;
        return json_encode($data);
    }
    public function check_msg(Request $request)
    {
        $paramData = $request->param();
        $sub_min_time = date('Y-m-d H:i:s', time()-10 * 60);
        $sms_code = SmsCodesModel::where('phone', $paramData['phone'])->where('code', $paramData['code'])->where('result', 0)->where('created_at', '>', $sub_min_time)->find();
        if (! $sms_code)
        {
            $data['errcode'] = 400;
            $data['errmsg']  = '验证码错误';
            return json_encode($data);
        }
        else
        {
            $data['errcode'] = 200;
            $data['errmsg']  = '验证通过';
            return json_encode($data);
        }
    }
    public function register(Request $request)
    {
        $paramData = $request->param();
        $openid = Session::get('openid');
        $accessToken = Session::get('accessToken');
        $param = [];
        $param['accessToken'] = $accessToken;
        $param['rnd'] = GetfourNumber(4);
        $param['appKey'] = 'P23GQJU5LH';
        $param['timestamp'] = time();
        $param['signType'] = 'md5';
        $sign = makeSign($param);

        $url = 'https://wxzhsc.sasseur.com/api/v3/member/regist?accessToken='.$accessToken.'&rnd='.$param['rnd'].'&appKey='.$param['appKey'].'&timestamp='.$param['timestamp'].'&sign='.$sign.'&signType=md5';
        
        $results = http_post_json($url, json_encode(['mallId'=>'AK5akKe8MqdedxU2','phone'=>$paramData['phone'],'portalWxOpenid'=>$openid]));//return_code是http状态码
        if ($results['errorCode'] == 'PUB-00000')
        {
            Db::table('mbyz_total')->where('total_object','mbyz')->setInc('register_number');
            $data['errcode'] = 200;
            $data['errmsg'] = $results['errorMessage'];
            $data['data'] = $results;
        }
        else
        {
            $data['errcode'] = 400;
            $data['errmsg']  = $results['errorMessage'];
        }
        return json_encode($data);
    }
}
